<?php

namespace app\admin\controller\shop;

use app\admin\model\money\Platform;
use app\admin\model\money\Refund;
use app\admin\model\Shop;
use app\admin\model\Shopmno;
use app\admin\model\Shoporderprofit;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\VbillService;
use app\common\controller\Backend;

/**
 * 店铺充值管理
 *
 * @icon fa fa-circle-o
 */
class Shopcharge extends Backend
{

    /**
     * Shopcharge模型对象
     * @var \app\admin\model\Shopcharge
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $noNeedRight = ['refund'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shopcharge;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['shop', 'user', 'charge'])
                ->where($where)
                ->where('Shopcharge.status', '<>', 'paying')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

                $list[$k]['desc'] = "";
                if ($v['charge'] != null) {
                    $list[$k]['desc'] = "充" . $v['charge']['amount'] . "得" . $v['charge']['get_amount'];
                }


            }
            $totalAmount = $this->model->where('status', 'not in', ['paying', 'refund'])->sum('amount');
            $todayAmount = $this->model->whereTime("create_time", 'today')->where('status', 'not in', ['paying', 'refund'])->sum('amount');

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['one' => $totalAmount, 'two' => $todayAmount]);


            return json($result);
        }
        return $this->view->fetch();
    }


    public function add($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;


                $shopChargeModel = new \app\admin\model\Shopcharge();
                $charge = $shopChargeModel->where('order_no', $params['order_no'])->find();
                if ($charge['status'] == 'refund') {
                    $this->error("此订单已退款无需发起操作");
                }
                $mnoModel = new Shopmno();
                $shopMno = $mnoModel->where('shop_id', $charge['shop_id'])->find();
                if (!empty($shopMno) && $shopMno == 100) {
                    $mno = $shopMno['mno'];
                } else {
                    $mno = $this->mno;
                }
                $req = array();
                $req['mno'] = $mno;
                $req['ordNo'] = getOrderSn();
                $req['origOrderNo'] = $charge['order_no'];
                $req['amt'] = $charge['amount'];

                $vbillService = new VbillService();
                $ret = $vbillService->refund($req);
                $result = json_decode($ret, true);
                if ($result['code'] != '0000') {
                    $this->error($result['msg']);
                }
                if ($result['respData']['bizCode'] != "0000") {
                    $this->error($result['respData']['bizMsg']);
                }
                $userBalanceModel = new Userbalance();

                $userBalanceModel->where('type', 'in')->where('order_id', $id)->delete();
                $shopOrderProfitModel = new Shoporderprofit();
                $shopOrderProfitModel->where('type', 'charge')->where('order_id', $id)->delete();

                $userOrderProfitModel = new Userorderprofit();
                $userOrderProfitModel->where('type', 'charge')->where('order_id', $id)->delete();

                $shopChargeModel->where('id', $charge['id'])->update(['status' => 'refund']);


                $this->success();
            }
        }


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $row['shop_id'])->find();
        $row['shop_name'] = $shop['name'];

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($row['shop_id'], $row['user_id']);
        $row['balance'] = $balance;
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    public function refund()
    {
        $id = $this->request->param('id');

        $shopChargeModel = new \app\admin\model\Shopcharge();
        $userBalanceModel = new Userbalance();

        $charge = $shopChargeModel->where('id', $id)->find();
        if ($charge['status'] == 'refund') {
            $this->error("此订单已退款无需发起操作");
        }

        if ($this->request->isAjax()) {
            $shopModel = new Shop();
            $shop = $shopModel->where('id', $charge['shop_id'])->find();
            $param = $this->request->param('row/a');

            $orderId = $param['charge_id'];
            $order_no = $param['order_no'];
            $get_amount = $param['get_amount'];
            $refund_amount = $param['refund_amount'];
            $balance = $param['balance'];
            $type = $param['type'];

            $charge = $shopChargeModel->where('id', $orderId)->find();
            $diffAmount = $charge['amount'] - $refund_amount;
            $is_refund = true;
            switch ($type) {
                case 0://退款退对应的充值余额
                    if ($balance < $get_amount) {
                        $this->error('剩余余额不足以退款');
                    }
                    if ($charge['amount'] < $refund_amount) {
                        $this->error('退款金额不得大于充值金额');
                    }

                    $this->payRefund($shop, $charge, $refund_amount);

                    $userBalanceModel->insert(['user_id' => $charge['user_id'], 'shop_id' => $charge['shop_id'], 'type' => 'out',
                        'amount' => $get_amount, 'order_id' => $orderId, 'mark' => '用户退款，退充值余额', 'create_time' => time()]);
                    break;

                case 1://退款清空余额
                    if ($charge['amount'] < $refund_amount) {
                        $this->error('退款金额不得大于充值金额');
                    }

                    $this->payRefund($shop, $charge, $refund_amount);
                    $userBalanceModel->insert(['user_id' => $charge['user_id'], 'shop_id' => $charge['shop_id'], 'type' => 'out',
                        'amount' => $balance, 'order_id' => $orderId, 'mark' => '用户退款，扣除全部余额', 'create_time' => time()]);
                    break;

                case 2:

                    $userBalanceModel->insert(['user_id' => $charge['user_id'], 'shop_id' => $charge['shop_id'], 'type' => 'out',
                        'amount' => $balance, 'order_id' => $orderId, 'mark' => '仅扣除全部余额', 'create_time' => time()]);
                    $is_refund = false;
                    break;
            }

            $shopOrderProfitModel = new Shoporderprofit();
            $userOrderProfitModel = new Userorderprofit();

            if ($diffAmount > 0) {
                $shopChargeModel->where('id', $orderId)->update(['amount' => $diffAmount, 'mark' => '用户充值' . $charge['amount'] . '元，退款' . $refund_amount . '元']);
                $profit = formatMoney($diffAmount * (100 - $shop['ratio'] - 0.006) / 100);
                if ($profit > 0) {
                    $shopOrderProfitModel->where('order_id', $charge['id'])->where('type', 'charge')->update(['amount' => $profit]);
                } else {
                    $shopOrderProfitModel->where('order_id', $charge['id'])->where('type', 'charge')->delete();
                }

            } else {
                $shopOrderProfitModel->where('order_id', $charge['id'])->where('type', 'charge')->delete();
                if ($is_refund) {
                    $shopChargeModel->where('id', $orderId)->update(['status' => 'refund']);
                }

            }
            $userOrderProfitModel->where('type', 'charge')->where('order_id', $charge['id'])->delete();

            $this->success('退款成功');
        }

        //查询用户余额
        $userBalance = $userBalanceModel->balance($charge['shop_id'], $charge['user_id']);
        $data = array();

        $data['share'] = '已分润';
        $data['amount'] = $charge['amount'];
        $data['balance'] = $userBalance;
        $data['order_no'] = $charge['order_no'];
        $data['charge_id'] = $charge['id'];
        $data['get_amount'] = $charge['get_amount'];
        $this->assign('row', $data);
        return $this->view->fetch();
    }

    public function refundV0()
    {
        $id = $this->request->param('id');

        $shopChargeModel = new \app\admin\model\Shopcharge();
        $charge = $shopChargeModel->where('id', $id)->find();
        if ($charge['status'] == 'refund') {
            $this->error("此订单已退款无需发起操作");
        }
        $mnoModel = new Shopmno();
        $shopMno = $mnoModel->where('shop_id', $charge['shop_id'])->find();
        if (!empty($shopMno) && $shopMno == 100) {
            $mno = $shopMno['mno'];
        } else {
            $mno = $this->mno;
        }
        $req = array();
        $req['mno'] = $mno;
        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $charge['order_no'];
        $req['amt'] = $charge['amount'];

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $result = json_decode($ret, true);
        if ($result['code'] != '0000') {
            $this->error($result['msg']);
        }
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
        $userBalanceModel = new Userbalance();

        $userBalanceModel->where('type', 'in')->where('order_id', $id)->delete();
        $shopOrderProfitModel = new Shoporderprofit();
        $shopOrderProfitModel->where('type', 'charge')->where('order_id', $id)->delete();

        $userOrderProfitModel = new Userorderprofit();
        $userOrderProfitModel->where('type', 'charge')->where('order_id', $id)->delete();

        $shopChargeModel->where('id', $charge['id'])->update(['status' => 'refund']);


        $this->success('退款成功');

    }

    protected function payRefund($shop, $charge, $refund_amount)
    {
        $req = array();
        $shopMonModel = new Shopmno();
        $shopMno = $shopMonModel->where('shop_id', $shop['id'])->find();
        if (!empty($shopMno) && $shopMno['mno'] == 100) {
            $req['mno'] = $shopMno['mno'];
        } else {
            $req['mno'] = $this->mno;
        }

        $req['ordNo'] = getOrderSn();
        $req['origOrderNo'] = $charge['order_no'];
        $req['amt'] = $refund_amount;

        $vbillService = new VbillService();
        $ret = $vbillService->refund($req);
        $result = json_decode($ret, true);

        if ($result['code'] != '0000') {
            $this->error($result['msg']);
        }
        if ($result['respData']['bizCode'] != "0000") {
            $this->error($result['respData']['bizMsg']);
        }
    }

}
